//
//  WRGestureVC.m
//  WRGesturePassword
//
//  Created by 王然 on 16/6/27.
//  Copyright © 2016年 wangran. All rights reserved.
//

#import "WRGestureViewController.h"
#import "WRGestureView.h"
#import "WRGestureIndicator.h"
#import "SettingMgr.h"
#import "GestureLocMgr.h"
#import "AIGestureLoc.h"
#define IndicatorV_Y (__SCREEN_WIDTH == 320 ? 31 * __MAIN_RATIO_375 : 51 * __MAIN_RATIO_375)    //小的展示view距离上方的距离
#define TextL_Y ( __SCREEN_HEIGHT == 480 ? 10 * __MAIN_RATIO_375 : 18 * __MAIN_RATIO_375)         //展示的label 距离上面一个控件的距离
#define GestureV_Y (__SCREEN_HEIGHT == 480 ? 39 * __MAIN_RATIO_375 : 49 * __MAIN_RATIO_375)      //展示的手势view 距离上面label 的距离
#define TextL_YAndY (__SCREEN_HEIGHT == 480 ? 15 * __MAIN_RATIO_375 : 19 * __MAIN_RATIO_375)   //展示的label 距离上面一个控件 变化的距离，如果有小展示indicatorV 则保持原来的位置 否则 减去这个高度
#define Word_Color_Normal (COLOR_RGBA(0xa7, 0xa7, 0xa7, 1))//常规文字颜色
#define Word_Color_Wrong (COLOR_RGBA(0xf0, 0x5f, 0x33, 1)) //错误文字颜色
#define Gesture_Color_Narmal (COLOR_RGBA(0xa7, 0xa7, 0xa7, 1)) //常规显示的圆点颜色
#define Gesture_Color_Select (COLOR_RGBA(0x20, 0x90, 0xe6, 1)) //正确选中的圆点颜色
#define Gesture_Color_Wrong (COLOR_RGBA(0xf0, 0x5f, 0x33, 1)) //错误选中的圆点颜色

@interface WRGestureViewController ()<WRGestureDelegate,UIViewControllerBackButtonDataSource , TriggerVister>

@property (nonatomic , strong) WRGestureIndicator * indicatorV;
@property (nonatomic , strong) UILabel * tipsL;
@property (nonatomic , strong) WRGestureView * gestureV;

@property (nonatomic , strong) UIView * gestureOutV;//盖在手势输入上面的页面 如果输入手势错误超过五次 显示

@property (nonatomic , strong) UIButton * tipsBtn;// 重设/(取消)的提示按钮

@property (nonatomic , assign) NSInteger remaindTimes;//剩余输入手势密码的机会
@property (nonatomic , strong) NSString* passwordOld; // 旧密码
@property (nonatomic , strong) NSString* passwordNew; // 新密码
@property (nonatomic , strong) NSString* passwordconfirm; // 确认密码
@property (nonatomic , strong) NSString* tip1; // 三步提示语
@property (nonatomic , strong) NSString* tip2;
@property (nonatomic , strong) NSString* tip3;

@property (nonatomic , assign) BOOL isErrorTips;//是否是错误提示 为了修改tipL的颜色

////本地保存一个5分钟的倒计时时间的原有时间 即保存密码出错五次的时间
//- (BOOL)canInputGesturePW;

@property (nonatomic , copy) void(^configSuccessClick)(NSString * passwordStr , BOOL success);

@property (nonatomic , strong) UIView * bottomTabbarFontV;

@end

@implementation WRGestureViewController
- (void)dealloc
{
    self.title = @"";
}
- (instancetype)initWithType:(GestureV_Type)type withPWOut:(BOOL)isTraPW withSuccess:(void(^)(NSString * passwordStr , BOOL success))successClick
{
    self = [super init];
    if (self) {
        self.gestureViewType = type;
        self.isTraOutOfPW = isTraPW;
        self.isNoNeedGesturePW = NO;
        if (successClick) self.configSuccessClick = successClick;
    }
    return self;
}
- (void)setGestureViewType:(GestureV_Type)gestureViewType
{
    _gestureViewType = gestureViewType;
    if (gestureViewType == GestureV_Type_Create) {
        [self cleanSaveTimeUserDefault];
        [self setTip: @"绘制手势密码"];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"手势密码";
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    [self createUI];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self requestData];

    if(self.gestureViewType != GestureV_Type_Create)
    {
        __weak __typeof(self) wself = self;
        [self navSetupLeftImageName:@"return_icon" action:^{
            [wself.navigationController popViewControllerAnimated:YES];
            if(wself.navLeftBtnClick)wself.navLeftBtnClick();
        }];
    }else {
        [self.bottomTabbarFontV setHidden:NO];
        [self navSetupLeftTitle:@"" action:nil];
    }
    
    if (self.gestureVCWillAppear) self.gestureVCWillAppear();
    if (self.isNoNeedGesturePW && self.gestureViewType != GestureV_Type_Create) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    switch (self.gestureViewType) {
        case GestureV_Type_Check:
            self.tipsL.text = @"请输入手势密码";
            break;
        case GestureV_Type_Create:
            [self cleanSaveTimeUserDefault];
            
            self.tipsL.text = @"绘制手势密码";
            break;
        case GestureV_Type_Modify:
            self.tipsL.text = @"请输入原手势密码";
            break;
        case GestureV_Type_Clean:
            self.tipsL.text = @"请输入手势密码以关闭";
            break;
        default:
            break;
    }
    self.remaindTimes = ([self getWrongTimes] > 0 ? [self getWrongTimes] :GestureMaxTimes);
    self.isErrorTips = NO;
    
    self.passwordOld = @"";
    self.passwordNew = @"";
    self.passwordconfirm = @"";
    
    [self updateTipBtnStatus];
}
- (void)setIsNoNeedGesturePW:(BOOL)isNoNeedGesturePW
{
    _isNoNeedGesturePW = isNoNeedGesturePW;
    if (isNoNeedGesturePW && self.gestureViewType != GestureV_Type_Create) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self loadSaveWrongTime];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.bottomTabbarFontV setHidden: YES];
    
}
- (void)requestData
{
    __weak __typeof(self) wself = self;
    [SETTINGMGR getGuestureInfoFinish:^() {
        wself.savedPassword = SETTINGMGR.gesturePWStr;
        wself.isNoNeedGesturePW = !SETTINGMGR.showGesturePassword;
    }];
}
#pragma mark -UIViewControllerBackButtonDataSource delegate
/**
 *  是否能右滑返回手势
 */
-(BOOL)viewControllerShouldGesturePopBack
{
    return NO;
}

- (void)setIsTraOutOfPW:(BOOL)isTraOutOfPW
{
    _isTraOutOfPW = isTraOutOfPW;
    if (self.gestureV) {
        self.gestureV.isTraOutOfPW = isTraOutOfPW;
    }
}
- (void)updateTipBtnStatus
{
    if ((self.gestureViewType == GestureV_Type_Create || self.gestureViewType == GestureV_Type_Modify) && (![self.passwordNew isEqualToString:@""])) { // 新建或修改 & 确认时 才显示按钮
        [self.tipsBtn setHidden:NO];
        [self.tipsBtn setTitle:@"点击此处以重新开始" forState:UIControlStateNormal];
        [self.tipsBtn setAlpha:1.0];
        
    }
    else if(self.gestureViewType == GestureV_Type_Check || (self.gestureViewType == GestureV_Type_Modify && ([self.passwordOld isEqualToString:@""] || (![self.passwordOld isEqualToString:self.savedPassword]))))
    {
        [self.tipsBtn setHidden:NO];
        [self.tipsBtn setTitle:@"忘记手势密码？" forState:UIControlStateNormal];
        [self.tipsBtn setAlpha:1.0];
    }
    else {
        [self.tipsBtn setHidden:YES];
        [self.tipsBtn setAlpha:0.0];
    }
    // 更新指示圆点
    if (((![self.passwordNew isEqualToString:@""]) && [self.passwordconfirm isEqualToString:@""]) || ( self.gestureViewType == GestureV_Type_Create) || (![self.passwordOld isEqualToString:@""] && self.gestureViewType == GestureV_Type_Modify && [self.tipsL.text isEqualToString:@"请输入新的密码"])){
        self.indicatorV.hidden = NO;
        [self.indicatorV setPasswordString:self.passwordNew];
        [self resetTipsL:IndicatorV_Y + Indicator_View_W + TextL_Y withFontSize:14 withTextColor:(self.isErrorTips ? Word_Color_Wrong : Word_Color_Normal)];
    } else {
        self.indicatorV.hidden = YES;
        [self resetTipsL:IndicatorV_Y + Indicator_View_W + TextL_Y - TextL_YAndY withFontSize:16 withTextColor:(self.isErrorTips ? Word_Color_Wrong : COLOR_HEXSTRING(@"#424242"))];

    }
    if(self.gestureViewType == GestureV_Type_Create)[self.gestureOutV setHidden:YES];
}
#pragma mark -重设置上方的提示label
- (void)resetTipsL:(CGFloat)top withFontSize:(CGFloat)fontSize withTextColor:(UIColor *)color
{
    
    [self.tipsL setTop:top];
    [self.tipsL setFont:FONT_DEFAULT_Light(fontSize)];
    [self.tipsL setTextColor:color];
}
- (void)createUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIWindow *mainWindow = [UIApplication sharedApplication].delegate.window;
    self.bottomTabbarFontV = [[[UIView viewWithFrame:CGRectMake(0, __MAIN_HEIGHT - __MAIN_TABBAR_HEIGHT - 1, __MAIN_WIDTH, __MAIN_TABBAR_HEIGHT + 1)] setupOnView:mainWindow] resetBackgroundColor:[UIColor whiteColor]];
    [self.bottomTabbarFontV setHidden:YES];
    
    self.indicatorV = [[WRGestureIndicator alloc]initWithFrame:CGRectMake((__SCREEN_WIDTH - Indicator_View_W) / 2 , IndicatorV_Y , Indicator_View_W , Indicator_View_W)withNormalC:Gesture_Color_Narmal withSelectColor:Gesture_Color_Select];
    self.indicatorV.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.indicatorV];
    
    self.tipsL = [[UILabel alloc]initWithFrame:CGRectMake(10, self.indicatorV.frame.origin.y + self.indicatorV.frame.size.height + TextL_Y, __SCREEN_WIDTH - 10 * 2, 20)];
    [self.tipsL setTextColor:Word_Color_Normal];
    [self.tipsL setTextAlignment:NSTextAlignmentCenter];
    [self.tipsL setFont:[UIFont systemFontOfSize:14]];
    [self.tipsL setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:self.tipsL];
    
    
    self.gestureV = [[WRGestureView alloc]initWithFrame:CGRectMake((__SCREEN_WIDTH - GestureV_H) / 2, self.tipsL.frame.origin.y + self.tipsL.frame.size.height + GestureV_Y - CircleBigLeft, GestureV_H, GestureV_H) withNormallColor:Gesture_Color_Narmal withSelectColor:Gesture_Color_Select withWrongColor:Gesture_Color_Wrong withIsTraOutPW:self.isTraOutOfPW];
    self.gestureV.delegate = self;
    self.gestureV.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.gestureV];
    
    self.gestureOutV = [UIView viewWithFrame:CGRectMake(CircleBigLeft, self.tipsL.frame.origin.y + self.tipsL.frame.size.height + GestureV_Y , GestureV_H - CircleBigLeft * 2, GestureV_H - CircleBigLeft * 2)];
    [self.view addSubview:self.gestureOutV];
    UIPanGestureRecognizer * panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(gestureOutVPan)];
    [self.gestureOutV setBackgroundColor:[UIColor clearColor]];
    [self.gestureOutV addGestureRecognizer:panGesture];
    [self.gestureOutV setHidden:[self loadSaveWrongTime]];
    
    self.tipsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.tipsBtn setFrame:CGRectMake(10, self.gestureV.frame.origin.y + self.gestureV.frame.size.height - CircleBigLeft + (__SCREEN_HEIGHT == 480 ? GestureV_Y / 2 : GestureV_Y) , __SCREEN_WIDTH - 10 * 2, 20)];
    [self.tipsBtn setBackgroundColor:[UIColor clearColor]];
    [self.tipsBtn addTarget:self action:@selector(tipButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.tipsBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [self.tipsBtn setTitleColor:Gesture_Color_Select forState:UIControlStateNormal];
    [self.view addSubview:self.tipsBtn];
    [self.view bringSubviewToFront:self.tipsBtn];
}
#pragma mark - 取出滑动出错的次数
- (NSInteger)getWrongTimes
{
    NSString * times = AIGESTURELOC.savePWWrongTimesNum;
    if ([times integerValue] > 0) {
        return [times integerValue];
    }else return 0;
}
#pragma mark - 超过5次后滑动 看是否将这个view 消失
- (void)gestureOutVPan
{
    BOOL isHidden = [self loadSaveWrongTime];
    [self.gestureOutV setHidden:isHidden];
    if (self.configSuccessClick) self.configSuccessClick(self.savedPassword , NO);
}
#pragma mark - 点击下方按钮
- (void)tipButtonClick
{
    self.passwordNew = @"";
    self.passwordconfirm = @"";
    [self setTip:self.tip1];
    [self updateTipBtnStatus];
    if (self.gestureViewType == GestureV_Type_Check || (self.gestureViewType == GestureV_Type_Modify && ([self.passwordOld isEqualToString:@""] || (![self.passwordOld isEqualToString:self.savedPassword])))) {
        if (self.lostPassword) self.lostPassword();
    }
}
#pragma mark - delegate 每次划完手势后
- (void)GestureWithPasswordStr:(NSString *)str
{
    switch (self.gestureViewType) {
        case GestureV_Type_Check:
            self.tip1 = @"请输入手势密码";
            [self checkPassword:str];
            break;
        case GestureV_Type_Create:
            self.tip1 = @"绘制手势密码";
            self.tip2 = @"再次绘制以确认";
            self.tip3 = @"与上次绘制不一致，请重新绘制";
            
            [self createPassWord:str];
            break;
        case GestureV_Type_Modify:
            if ([self.passwordOld isEqualToString:@""]) {
                self.tip1 = @"请输入原手势密码";
                [self checkPassword:str];
            }else
            {
                self.tip1 = @"绘制手势密码";
                self.tip2 = @"再次绘制以确认";
                self.tip3 = @"密码修改成功";
                [self createPassWord:str];
            }
            break;
        case GestureV_Type_Clean:
            self.tip1 = @"请输入手势密码以关闭";
            self.tip2 = @"关闭手势密码成功";
            [self checkPassword:str];
            break;
        default:
            break;
    }
    
    [self updateTipBtnStatus];
}
#pragma mark -重置输入密码次数事件
- (void)resetGestureMaxTimes
{
    self.remaindTimes = GestureMaxTimes;
    AIGESTURELOC.savePWWrongTimesNum = [NSString stringWithFormat:@"%zd",self.remaindTimes];
}
#pragma mark - 检查 ／更新密码
- (void)checkPassword:(NSString *)string
{
    //验证密码正确
    if ([string isEqualToString:self.savedPassword]) {
        //验证成功一次 便清除保存的错误的次数
        AIGESTURELOC.savePWWrongTimesNum = [NSString stringWithFormat:@"%zd",GestureMaxTimes];
        self.remaindTimes = [self getWrongTimes];
        switch (self.gestureViewType) {
            case GestureV_Type_Modify:
            {
                self.passwordOld  = string;//设置旧密码，说明是在修改
                [self setTip:@"请输入新的密码"];//这里和下面的delgate不一致
            }
                break;
            case GestureV_Type_Clean:
            {
                self.savedPassword = @"";
                [self hide];
                
                [self showAlert:self.tip2];
            }
                break;
            default://验证成功
            {
                [self hide];
                [self.navigationController popViewControllerAnimated:YES];
                if (self.configSuccessClick) self.configSuccessClick(self.savedPassword , YES);
            }
                break;
        }
    }//验证密码错误
    else if(string.length > 0)
    {
        if (string.length >= GestureMinLength) {
            self.remaindTimes --;
            AIGESTURELOC.savePWWrongTimesNum = [NSString stringWithFormat:@"%zd",self.remaindTimes];

            if (self.remaindTimes > 0) {
                if (1 == self.remaindTimes) {
                    [self setErrorTip:[NSString stringWithFormat:@"最后的一次机会咯!"] errorPswd:string];
                }
                else
                {
                    [self setErrorTip:[NSString stringWithFormat:@"密码错误，还可以再输入%zd次", self.remaindTimes] errorPswd:string];
                }
            }else
            {
                if(self.gestureViewType != GestureV_Type_Create)
                {
                    [self setErrorTip:[NSString stringWithFormat:@"多次输入错误,请5分钟后再试"] errorPswd:string];
                }
                //            [self showAlert:@"为了您的账户安全已注销您的账户,请重新登录！"];
                self.savedPassword = @"";
                
                [self saveWrongTime];
                if (self.configSuccessClick) self.configSuccessClick(self.savedPassword , NO);
            }
        }else
        {
            [self setErrorTip:[NSString stringWithFormat:@"至少连接%zd个点，请重新绘制",GestureMinLength]errorPswd:string];
        }
        
    }
}
#pragma mark - 保存当前出错5次的时间
- (void)saveWrongTime
{
    [self.gestureOutV setHidden:NO];
    self.remaindTimes = 0;
    [GESTURELOCMGR saveWrongFiveTime];
}
#pragma mark - 返回是否是已经超过了五分钟 是返回yes  否则返回no
- (BOOL)loadSaveWrongTime
{
    BOOL ifOutFiveMinute = [GESTURELOCMGR loadSaveWrongTimeOutFiveMinute];
    if (!ifOutFiveMinute) {
       if(self.gestureViewType != GestureV_Type_Create)
       {
           [self setErrorTip:[NSString stringWithFormat:@"多次输入错误,请5分钟后再试"] errorPswd:@""];
       }
        [self resetGestureMaxTimes];
        return NO;
    }else
    {
        return YES;
    }
}
#pragma mark - 如果是新建清除本地缓存的五分钟
- (void)cleanSaveTimeUserDefault
{
    [self.gestureOutV setHidden:YES];
    AIGESTURELOC.savePWWrongTime = @"";
}
#pragma mark - 提示信息
- (void)showAlert:(NSString*)string
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:string delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alert show];
}
#pragma mark - 创建密码
- (void)createPassWord:(NSString *)string
{
    [self cleanSaveTimeUserDefault];
    if (string.length >= GestureMinLength) {
        //输入密码
        if ([self.passwordNew isEqualToString:@""] && [self.passwordconfirm isEqualToString:@""]) {
            self.passwordNew = string;
            [self setTip:self.tip2];
        }
        //确认输入密码
        else if((![self.passwordNew isEqualToString:@""]) && [self.passwordconfirm isEqualToString:@""])
        {
            self.passwordconfirm = string;
            if ([self.passwordNew isEqualToString:self.passwordconfirm]) {//成功
                self.savedPassword = string;
                [self hide];
                [self setTip:self.tip3];
                
                AIGESTURELOC.savePWWrongTimesNum = [NSString stringWithFormat:@"%zd",GestureMaxTimes];
                self.remaindTimes = [self getWrongTimes];
                [self.navigationController popViewControllerAnimated:YES];
                if (self.configSuccessClick) self.configSuccessClick(self.savedPassword , YES);
            }else
            {
                self.passwordconfirm = @"";
                [self setTip:self.tip2];
                [self setErrorTip:@"与上次绘制不一致，请重新绘制" errorPswd:string];
            }
        }
    }else
    {
        [self setErrorTip:[NSString stringWithFormat:@"至少连接%zd个点，请重新绘制",GestureMinLength]errorPswd:string];
    }
    
}
#pragma mark - 成功后返回
- (void)hide
{
    switch (self.gestureViewType) {
        case GestureV_Type_Check:
            break;
        case GestureV_Type_Create:
        case GestureV_Type_Modify:
        {
            self.savedPassword =self.passwordNew;
        }
            break;
        case GestureV_Type_Clean:
        default:
        {
            self.savedPassword = @"";
        }
            break;
    }
    
}
#pragma mark - 设置错误
- (void)setErrorTip:(NSString*)tip errorPswd:(NSString*)string
{
    // 显示错误点点
    [self.gestureV showErrorClircles:string];
    
    // 直接_变量的坏处是updateTipBtnStatus
    [self.tipsL setText:tip];
    [self.tipsL setTextColor:Word_Color_Wrong];
    self.isErrorTips = YES;
    [self shakeAnimationForView:self.tipsL];
}
#pragma mark 抖动动画
- (void)shakeAnimationForView:(UIView *)view
{
    CALayer *viewLayer = view.layer;
    CGPoint position = viewLayer.position;
    CGPoint left = CGPointMake(position.x - 10, position.y);
    CGPoint right = CGPointMake(position.x + 10, position.y);
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [animation setFromValue:[NSValue valueWithCGPoint:left]];
    [animation setToValue:[NSValue valueWithCGPoint:right]];
    [animation setAutoreverses:YES]; // 平滑结束
    [animation setDuration:0.08];
    [animation setRepeatCount:3];
    
    [viewLayer addAnimation:animation forKey:nil];
}
#pragma mark -显示提示
- (void)setTip:(NSString *)tip
{
    [self.tipsL setText:tip];
    [self.tipsL setTextColor:Word_Color_Normal];
    self.isErrorTips = NO;
    self.tipsL.alpha = 0 ;
    __weak __typeof(self) wself = self;
    [UIView animateWithDuration:0.5 animations:^{
        wself.tipsL.alpha = 1;
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
